package com.swust.security.controller;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author hqf
 * @Date Created in 2021/9/12 16:48
 * @Description
 * index 只要有管理员角色都能访问
 * 而增删改查操作需要赋予对应的权限
 * 比如 有增加操作需要用户
 * ROLE_admin,add
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @GetMapping("/index")
    public String index(HttpSession session, Model model){
        // 获取当前登录的用户 第一种方式
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = userDetails.getUsername();
        System.out.println("【1】当前登录用户:"+username);
        // 第二种方式
        SecurityContextImpl securityContext = (SecurityContextImpl)session.getAttribute("SPRING_SECURITY_CONTEXT");
        String username2 = securityContext.getAuthentication().getName();
        System.out.println("【2】当前登录用户:"+username2);
        // 获得当前用户所拥有的权限
        List<GrantedAuthority> authorities = (List<GrantedAuthority>) securityContext
                .getAuthentication().getAuthorities();
        System.out.println("Authority:");
        for (GrantedAuthority grantedAuthority : authorities) {
            System.out.println(grantedAuthority.getAuthority());
        }
        model.addAttribute("username",username);
        model.addAttribute("auths",authorities);
        return "main";
    }

    @GetMapping("/add")
    @ResponseBody
    public String add(){
        return "add";
    }

    @GetMapping("/delete")
    @ResponseBody
    public String delete(){
        return "delete";
    }

    @GetMapping("/update")
    @ResponseBody
    public String update(){
        return "update";
    }

    @GetMapping("/select")
    @ResponseBody
    public String select(){
        return "select";
    }
}
